package cn.edu.ldh.toolapp.util;

import ohos.net.NetHandle;
import ohos.net.NetManager;
import javax.net.ssl.HttpsURLConnection;
import java.io.IOException;
import java.io.InputStream;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;

public class HttpUtil {

    private static InputStream inputStream;
    private static HttpsURLConnection connection;

    /**
     * 获取网络图片
     * @param imgUrl;
     * @param method;
     * @return inputStream;
     **/
    public static InputStream getInputStream(String imgUrl, String method) {
        NetManager netManager = NetManager.getInstance(null);
        if(!netManager.hasDefaultNet()) {
            return null;
        }
        NetHandle netHandle = netManager.getDefaultNet();
        try {
            URL url = new URL(imgUrl);
            URLConnection urlConnection = netHandle
                    .openConnection(url, Proxy.NO_PROXY);
            if(urlConnection instanceof HttpsURLConnection) {
                connection = (HttpsURLConnection) urlConnection;
            }
            connection.setRequestMethod(method);
            connection.connect();
            inputStream = connection.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return inputStream;
    }

    //关闭
    public static void closeStream() {
        try {
            if(inputStream == null) {
                return;
            }
            inputStream.close();
            if(connection == null) {
                return;
            }
            connection.disconnect();
        }catch (IOException e) {
            e.printStackTrace();
        }
    }
}
